<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/projects.php');

$user_id = $_SESSION['user_id'];
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'add';

// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =
array('act_add');

/* 显示页面的action列表 */
$ui_arr = array('add', 'act_add','act_addok','edit', 'profile',
'message_list', 'get_password', 'reset_password', 'default','validate_email','aboutme','photo','browse','view_project','project_proposal','award','view_project');

/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_arr))
{
	
    assign_template();
	$smarty->assign('page_title', 'Login'); // 页面标题
    include_once(ROOT_PATH .'includes/lib_clips.php');
    $smarty->assign('info',        get_user($user_id));
	
    $smarty->assign('data_dir',   DATA_DIR);   // 数据目录
    $smarty->assign('action',     $action);
    $smarty->assign('lang',       $_LANG);
}


/*------------------------------------------------------ */
//-- add project
/*------------------------------------------------------ */
if($action == 'add')
{
	
	if (!$_SESSION['user_id'])
	{
		$smarty->assign('login_flag', 0);
	}
	else
	{
		/*判断用户类型，只有exerciser才可以发布任务*/
		if($_SESSION['user_type'] != 2)
		{
			show_message($_LANG['not_exerciser'], $_LANG['back_up_page'], 'index.php', 'info');
		}
		$smarty->assign('login_flag', 1);		
	}
	
    /* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainertype');
	$trainertype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainingtype');
	$trainingtype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('sessionlength');
	$length=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('budget');
	$budget=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('quoting');
	$quoting=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('sessionstype');
	$sessions=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('friendsnum');
	$friends=$db->getAll($sql);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('city') ;
	$citys=$db->getAll($sql);
	$tmp = '';
	foreach($citys as $city)
	{
		$tmp = $tmp.$city['city_name'].',';
	}
	    
    $smarty->assign('trainertype', $trainertype);
    $smarty->assign('trainingtype', $trainingtype);
	$smarty->assign('length', $length);
	$smarty->assign('budget', $budget);
	$smarty->assign('length', $length);
	$smarty->assign('quoting', $quoting);
	$smarty->assign('sessions', $sessions);
	$smarty->assign('friends', $friends);
	$smarty->assign('citys', $tmp);
			
	$smarty->display('project_add.dwt');
}

/*------------------------------------------------------ */
//-- edit project
/*------------------------------------------------------ */
elseif($action == 'edit')
{
	if (!$_SESSION['user_id'])
	{
		show_message($_LANG['not_login'], $_LANG['back_up_page'], 'projects.php', 'info');
	}
	else
	{
		/*判断用户类型，只有exerciser才可以发布任务*/
		if($_SESSION['user_type'] != 2)
		{
			show_message($_LANG['not_exerciser'], $_LANG['back_up_page'], 'projects.php', 'info');
		}
		$smarty->assign('login_flag', 1);
		
		/*获取项目id*/
		$getpid  = isset($_REQUEST['pid']) ? intval($_REQUEST['pid']) : 0;
		if($getpid == 0)
		{
			show_message($_LANG['no_project_id'], $_LANG['back_up_page'], 'projects.php', 'info');
		}
		$smarty->assign('pid', $getpid);		
	}
		
	/* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainertype');
	$trainertype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainingtype');
	$trainingtype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('sessionlength');
	$length=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('budget');
	$budget=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('quoting');
	$quoting=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('sessionstype');
	$sessions=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('friendsnum');
	$friends=$db->getAll($sql);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('city');
	$citys=$db->getAll($sql);
	$tmp = '';
	foreach($citys as $city)
	{
		$tmp = $tmp.$city['city_name'].',';
	}
		
	#获取任务详细信息
	$sql = 'SELECT * ' .'FROM ' . $GLOBALS['ecs']->table('projects') ." WHERE pid='$getpid' ";	
	$project=$db->getRow($sql);
			
	$smarty->assign('trainertype', $trainertype);
    $smarty->assign('trainingtype', $trainingtype);
	$smarty->assign('length', $length);
	$smarty->assign('budget', $budget);
	$smarty->assign('length', $length);
	$smarty->assign('quoting', $quoting);
	$smarty->assign('sessions', $sessions);
	$smarty->assign('friends', $friends);
	$smarty->assign('project', $project);
	$smarty->assign('pid', $getpid);
	$smarty->assign('citys', $tmp);
	
	$smarty->display('project_add.dwt');
}

/*------------------------------------------------------ */
//-- browse projects
/*------------------------------------------------------ */
elseif($action == 'browse')
{
	$_SESSION['trainer_type'] = 0;
	$_SESSION['training_type'] = 0;
	$_SESSION['budget_type'] = 0;
	$_SESSION['quoting_type'] = 0;

	/* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainertype');
	$trainertype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainingtype');
	$trainingtype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('budget');
	$budget=$db->getAll($sql);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('quoting');
	$quoting=$db->getAll($sql);
	
	$fctime= date("Y-m-d",time());
	
	/* ÿһ ڽܽÿһг߱ģunfinished*/
    $sql = 'SELECT a.*, b.budgetType, u.user_name, u.firstname, u.lastname, g.genderType ' .'FROM ' . $GLOBALS['ecs']->table('projects') . ' AS a JOIN '. $GLOBALS['ecs']->table('budget') . ' AS b JOIN ' .$GLOBALS['ecs']->table('users') . ' AS u JOIN ' .$GLOBALS['ecs']->table('gender')." AS g "." WHERE  a.featuredFlag=1 AND a.budget=b.num AND a.uid=u.user_id AND u.sex=g.xid AND a.createdDate='$fctime' AND status != 0";
	$featurelist=$db->getAll($sql);
	$featurecount=count($featurelist);
	
	/* Caculate The Remaining Time of The Project */
	for($i=0; $i<count($featurelist); $i++)
	{
		$createtime=strtotime($featurelist[$i]['createdDate']);
		if($featurelist[$i].quoting == 1)
		{
			$endtime = $createtime + 14 * 86400;
		}
		else
		{
			$endtime = $createtime + 30 * 86400;
		}
	    
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours ago";
    	}else if($hours>0){
      		 $temp="$hours hours ago";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes ago";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$featurelist[$i]['lefttime']=$temp;	
		
		if(	$temp == "over")
		{
			$sql = "UPDATE " . $ecs->table('projects') . " SET status=5 "." WHERE pid='".$featurelist[$i]['pid']."'";					
			$db->query($sql);
		}
		
	}
	
	/* Get All Projects */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects'). " AS p JOIN ". $GLOBALS['ecs']->table('users'). " AS u ". " WHERE status != 0 AND p.uid = u.user_id ";
	$tasklist=$db->getAll($sql);
	$taskcount=count($tasklist);
		
	$record_count = $taskcount;
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 10;
	$pager = get_pager('projects.php', array('act' => 'browse'), $record_count, $page, $pagesize);
	$fitness_lists = get_projects_list($pagesize, $pager['start']);
		
    $smarty->assign('trainertype', $trainertype);
    $smarty->assign('trainingtype', $trainingtype);
	$smarty->assign('budget', $budget);
	$smarty->assign('quoting', $quoting);
	$smarty->assign('featurelist', $featurelist);
	$smarty->assign('pager', $pager);
	$smarty->assign('tasklist', $fitness_lists);
	$smarty->assign('featurecount', $featurecount);
	$smarty->assign('taskcount', $taskcount);
	
    $smarty->display('projects_browse.dwt');
}

/*------------------------------------------------------ */
//-- view project
/*------------------------------------------------------ */
elseif ($action == 'view_project')
{
	/* Get Project Id */
	$getpid  = isset($_REQUEST['pid']) ? trim($_REQUEST['pid']) : 'nothing';
	$order  = isset($_REQUEST['order']) ? trim($_REQUEST['order']) : 'DESC';
	$sort_type  = isset($_REQUEST['sort_type']) ? trim($_REQUEST['sort_type']) : 'ppid';
		
	/* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('proposaledtrainingtype');
	$proposaledtrainingtype=$db->getAll($sql);
	
	/* According to the pid, get the project from database */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects').' AS p JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u JOIN '.$GLOBALS['ecs']->table('budget') . ' AS b JOIN '.$GLOBALS['ecs']->table('trainertype').' AS t JOIN ' .$GLOBALS['ecs']->table('trainingtype').' AS tt JOIN ' .$GLOBALS['ecs']->table('sessionstype').' AS s JOIN ' .$GLOBALS['ecs']->table('sessionlength').' AS l ' ." WHERE p.pid='".$getpid."' AND p.uid=u.user_id AND p.budget=b.num AND p.trainerType=t.num AND p.trainingType=tt.num AND p.sessions=s.num AND p.length=l.num ";
	$tasklist = $db->getRow($sql);
			
	/* According to the pid, get the proposal from database */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ' ." WHERE pp.pid='".$getpid."' AND pp.uid=u.user_id ";
	$proposalslist = $db->getALL($sql);
	
	$record_count = count($proposalslist);
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 10;
	$pager = get_pager('projects.php', array('act' => 'view_project','pid' => $getpid), $record_count, $page, $pagesize);
	$fitness_lists = get_proposals_list($pagesize, $pager['start'], $getpid, $order, $sort_type);
	
	if($_SESSION['user_type'] == 1)
	{
		/* According to the pid, get the proposal from database */
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ' ." WHERE pp.pid='".$getpid."' AND pp.uid='".$_SESSION['user_id']."' ";
		$myproposal = $db->getRow($sql);
		$smarty->assign('myproposal', $myproposal);
	}
	
	$createtime=strtotime($tasklist['createdDate']);
		
	if($tasklist['quoting'] == 1)
	{
		$endtime = $createtime + 14 * 86400;
	}
	else
	{
		$endtime = $createtime + 30 * 86400;
	}
	
	$nowtime=time();
    $days=($endtime - $nowtime)/86400;
    $new_day=explode('.',$days);
	
    $hours=floor(($endtime - $nowtime)/3600);

   	$hours_day=$hours-($new_day[0]*24);

    $minutes=floor(($endtime - $nowtime)/60);

    if($new_day[0]>0){
    	$temp="$new_day[0] days $hours_day hours";
    }else if($hours>0){
      	$temp="$hours hours";
   	}else if($hours_day==0){
      	$temp="$minutes minutes";
    }else if($hours_day<0){
     	$temp="over";
    }
	$tasklist['lefttime']=$temp;
	$tasklist['friends'] = $tasklist['friends'] + 1;
	
	$smarty->assign('proposaledtrainingtype', $proposaledtrainingtype);
	$smarty->assign('tasklist', $tasklist);
	$smarty->assign('pager', $pager);
	$smarty->assign('proposalslist', $fitness_lists);
	$smarty->assign('info',        get_user($user_id));
	
	if($tasklist['uid'] == $_SESSION['user_id'])
	{
		$smarty->assign('flag', 1);
	}
	else
	{
		$smarty->assign('flag', 0);
	}
	
	if($order == 'DESC')
	{
		$smarty->assign('order', 'ASC');
	}
	else
	{
		$smarty->assign('order', 'DESC');
	}
	$smarty->display('view_project.dwt');
}

/*------------------------------------------------------ */
//-- Project Proposal
/*------------------------------------------------------ */
elseif ($action == 'project_proposal')
{
	$getpid=$_GET['pid'];
	
	/*获取夺标方案ppid值*/
	$sql = "SELECT ppid "." FROM " . $GLOBALS['ecs']->table('proposals')  ." WHERE pid='".$getpid."' AND awarded=1  AND accepted=1 ";
	$ppid= $db->getRow($sql);
	
	$getppid=isset($_REQUEST['ppid'])?intval($_REQUEST['ppid']):$ppid['ppid'];
		
	if($_SESSION['user_type'] != 2)
	{
		/* According to the pid, get the project from database */
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects').' AS p JOIN ' . $GLOBALS['ecs']->table('proposals') . ' AS pp JOIN '.$GLOBALS['ecs']->table('users') . ' AS u JOIN '.$GLOBALS['ecs']->table('budget') . ' AS b JOIN '.$GLOBALS['ecs']->table('trainertype').' AS t JOIN ' .$GLOBALS['ecs']->table('trainingtype').' AS tt JOIN ' .$GLOBALS['ecs']->table('sessionstype').' AS s JOIN ' .$GLOBALS['ecs']->table('sessionlength').' AS l JOIN '.$GLOBALS['ecs']->table('proposaledtrainingtype')." AS pt "." WHERE pp.ppid='".$getppid."' AND pp.pid=p.pid  AND pp.uid=u.user_id AND p.budget=b.num AND p.trainerType=t.num AND p.trainingType=tt.num AND p.sessions=s.num AND p.length=l.num AND pp.proposaledTrainingType=pt.xid ";
		$proposal= $db->getRow($sql);
		$proposal['friends'] = $proposal['friends'] + 1;
	}
	else
	{
		/* According to the pid, get the proposal from database */
		$sql = "SELECT * , pp.uid AS pp_userid, p.uid AS p_userid "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN '.$GLOBALS['ecs']->table('projects') . ' AS p JOIN '.$GLOBALS['ecs']->table('users')." AS u JOIN ".$GLOBALS['ecs']->table('proposaledtrainingtype')." AS pt "." WHERE pp.ppid='".$getppid."' AND pp.pid=p.pid AND pp.uid=u.user_id AND pp.proposaledTrainingType=pt.xid ";
		$proposal= $db->getRow($sql);
	
		$smarty->assign('info_b',   get_user($proposal['pp_userid']));
				
		if($proposal['p_userid'] == $_SESSION['user_id'])
		{
			/* 如果用户为项目发布者，则将该proposal标记为watch */
			$sql = "UPDATE ". $GLOBALS['ecs']->table('proposals'). " SET watched=1 "." WHERE ppid='".$getppid."' ";
			$db->query($sql);
			
			$smarty->assign('flag', 1);
		}
		else
		{
			$smarty->assign('flag', 0);
		}
		
	}
		
	/* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('proposaledtrainingtype');
	$proposaledtrainingtype=$db->getAll($sql);
	$smarty->assign('proposaledtrainingtype', $proposaledtrainingtype);
		
	$smarty->assign('proposal', $proposal);
	$smarty->display('project_proposal.dwt');
}

/*------------------------------------------------------ */
//-- review
/*------------------------------------------------------ */
elseif ($action == 'review')
{
	$getpid=$_GET['pid'];
		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN '.$GLOBALS['ecs']->table('users') . ' AS u JOIN '.$GLOBALS['ecs']->table('proposaledtrainingtype') . ' AS pt '." WHERE pp.pid='".$getpid."' AND pp.accepted=1 AND pp.uid=u.user_id AND pp.proposaledTrainingType=pt.xid ";
	
	$proposal= $db->getRow($sql);
		
	$smarty->assign('proposal', $proposal);
	$smarty->display('review_trainer.dwt');
}

/*------------------------------------------------------ */
//-- review
/*------------------------------------------------------ */
elseif ($action == 'review_client')
{
	$getppid=$_GET['ppid'];
	$getpid=$_GET['pid'];
		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects').' AS p JOIN '.$GLOBALS['ecs']->table('users') . ' AS u '." WHERE p.pid='".$getpid."' AND p.uid=u.user_id ";
	
	$project= $db->getRow($sql);
		
	$smarty->assign('project', $project);
	$smarty->assign('ppid',$getppid);
	$smarty->display('review_client.dwt');
}

/*------------------------------------------------------ */
//-- act review
/*------------------------------------------------------ */
elseif($action == 'act_review')
{
	$getppid=$_POST['ppid'];
	$getpid=$_POST['pid'];
	$review=$_POST['review'];
	$uid=$_POST['uid'];
	$score=$_POST['score'];
	$complete_select=$_POST['complete_select'];
	
	/*get trainer information*/
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('users').' AS u JOIN '.$GLOBALS['ecs']->table('proposals') . ' AS p '."WHERE p.ppid='$getppid' AND u.user_id=p.uid  ";
	$trainer = $db->getRow($sql);
	send_alert_email($trainer['user_id'], $trainer['user_name'], $trainer['email'], 'review_notice', 'user.php?user_id='.$trainer['user_id']);
		
	$sql = "INSERT INTO " . $ecs->table('review') . "( reviewer_id, reviewed_id, review_content, rank_score) VALUES ('" . $_SESSION['user_id'] . "', '" . $uid. "', '" . $review. "', '" . $score. "')";
	if($db->query($sql) != false)
	{
		if($complete_select == 1)
		{
			$sql = "UPDATE " . $ecs->table('projects') . " SET status=5 "." WHERE pid='".$getpid."'";
						
			if($db->query($sql) == false)
			{
				show_message("Set Project Status to 3 failled!", $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
			}
		}
		else
		{
			$sql = "UPDATE " . $ecs->table('projects') . " SET status=4 "." WHERE pid='".$getpid."'";
						
			if($db->query($sql) == false)
			{
				show_message("Set Project Status to 3 failled!", $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
			}
		}
		
		$sql = "UPDATE " . $ecs->table('users') . "SET rank_points = rank_points + '$score' , rank_number = rank_number + 1 WHERE user_id = '$uid'";
    	$db->query($sql);	
		
		
				
		show_message('Review completed!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}
	else
	{
		show_message('Review trainer failed!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}	
}


/*------------------------------------------------------ */
//-- act review
/*------------------------------------------------------ */
elseif($action == 'act_review_client')
{	
	$review=$_POST['review'];
	$uid=$_POST['uid'];
	$score=$_POST['score'];
	$getppid=$_POST['ppid'];
		
	/*get trainer information*/
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='$uid' ";
	$client = $db->getRow($sql);
	send_alert_email($client['user_id'], $client['user_name'], $client['email'], 'review_notice', 'user.php?user_id='.$client['user_id']);
		
	$sql = "INSERT INTO " . $ecs->table('review') . "( reviewer_id, reviewed_id, review_content, rank_score) VALUES ('" . $_SESSION['user_id'] . "', '" . $uid. "', '" . $review. "', '" . $score. "')";
	if($db->query($sql) != false)
	{			
		$sql = "UPDATE " . $ecs->table('users') . "SET rank_points = rank_points + '$score' , rank_number = rank_number + 1 WHERE user_id = '$uid'";
    	$db->query($sql);	
		
		$sql = "UPDATE " . $ecs->table('proposals') . "SET review = 1 WHERE ppid = '$getppid'";
		
    	$db->query($sql);	
				
		show_message('Review client successfully!', $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}
	else
	{
		show_message('Review client failed!', $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}	
}


/*------------------------------------------------------ */
//-- Award Letter
/*------------------------------------------------------ */
elseif($action == 'award')
{
	$getppid=$_GET['ppid'];
		
	/* According to the pid, get the proposal from database */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN '.$GLOBALS['ecs']->table('projects') . ' AS p JOIN '.$GLOBALS['ecs']->table('users') . ' AS u '." WHERE pp.ppid='".$getppid."' AND pp.pid=p.pid AND p.uid=u.user_id ";
	$awardletter= $db->getRow($sql);
	$fctime= date("Y-m-d H:i:s",time() + 24*60*60*2);
	$awardletter['awardDate']=$fctime;
			
	$smarty->assign('awardletter', $awardletter);
	$smarty->display('award_letter.dwt');
}

/*------------------------------------------------------ */
//-- Act Award
/*------------------------------------------------------ */
elseif($action == 'act_award')
{
	$getpid=$_GET['pid'];
	$getppid=$_GET['ppid'];
	$contactPhone=$_POST['contactPhone'];

	$sql = "UPDATE " . $ecs->table('projects') . " SET status=2, contactPhone='$contactPhone' "." WHERE pid='".$getpid."'";
	if($db->query($sql) != false)
	{
	}
	else
	{
		show_message($_LANG['AboutMe_fail'], $_LANG['back_up_page'], 'exerciser.php', 'info');
	}
	$fctime= date("Y-m-d H:i:s",time() + 24*60*60*2);
	$sql = "UPDATE " . $ecs->table('proposals') . " SET awarded=1 , message='".$_POST['msg']."', awardDate='$fctime' "." WHERE ppid='".$getppid."'";
	if($db->query($sql) != false)
	{
	}	
	else
	{
		show_message($_LANG['AboutMe_fail'], $_LANG['back_up_page'], 'exerciser.php', 'info');
	}
	
	/* Update Database */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('users').' AS u JOIN '.$GLOBALS['ecs']->table('projects') . ' AS p '."WHERE p.pid='$getpid' AND u.user_id=p.uid  ";
	$value = $db->getRow($sql);
	$value['projects_awarded'] = $value['projects_awarded'] + 1;	
	
	/*get trainer information*/
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('users').' AS u JOIN '.$GLOBALS['ecs']->table('proposals') . ' AS p '."WHERE p.ppid='$getppid' AND u.user_id=p.uid  ";
	$trainer = $db->getRow($sql);
	send_alert_email($trainer['user_id'], $trainer['user_name'], $trainer['email'], 'award_notice', 'user.php?user_id='.$trainer['user_id']);
	
	
	$sql = "UPDATE " . $GLOBALS['ecs']->table('users').' AS u JOIN '.$GLOBALS['ecs']->table('projects') . ' AS p '. " SET projects_awarded='$value[projects_awarded]', status=2 "." WHERE p.pid='$getpid' AND u.user_id=p.uid ";
	if($db->query($sql) != false)
	{
		show_message('Award Successfully!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}
	else
	{
		show_message('Award Failed!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}	
}

/*------------------------------------------------------ */
// Search
/*------------------------------------------------------ */
elseif ($action == 'search')
{
	$trainer_type = isset($_REQUEST['trainertype']) ? intval($_REQUEST['trainertype']) : intval($_SESSION['trainer_type']);
    $training_type = isset($_REQUEST['trainingtype']) ? intval($_REQUEST['trainingtype']) : intval($_SESSION['training_type']);
	$budget_type = isset($_REQUEST['budget']) ? intval($_REQUEST['budget']) : intval($_SESSION['budget_type']);
    $quoting_type = isset($_REQUEST['close_open']) ? intval($_REQUEST['close_open']) : intval($_SESSION['quoting_type']);
	$sort = isset($_REQUEST['sort_type']) ? trim($_REQUEST['sort_type']) : 'pid';
	
	$_SESSION['trainer_type'] = $trainer_type;
	$_SESSION['training_type'] = $training_type;
	$_SESSION['budget_type'] = $budget_type;
	$_SESSION['quoting_type'] = $quoting_type;
	
	$keywords = isset($_REQUEST['keywords']) ? trim($_REQUEST['keywords']) : '';
	$my_address = isset($_REQUEST['my_address']) ? trim($_REQUEST['my_address']) : '';
    
	if($trainer_type != 0)
	{
		$condition = " AND a.trainerType='$trainer_type' ";
	}
	else
	{
		$condition = "";
	}
	
	if($training_type != 0)
	{
		$condition = $condition." AND a.trainingType='$training_type' ";
	}
	
	if($budget_type != 0)
	{
		$condition = $condition." AND a.budget='$budget_type' ";
	}
		
	if($quoting_type == 2)
	{
		$condition = $condition." AND ( a.status = 0 OR a.status = 2 OR a.status = 3 OR a.status = 4 OR a.status = 5) ";
	}
	elseif($quoting_type == 1)
	{
		$condition = $condition." AND ( a.status = 1 ) ";
	}
	
	if($my_address != '')
	{
		$condition = $condition." AND a.city LIKE '%$my_address%' ";
	}
	
	if($keywords != '')
	{
		$condition = $condition." AND (a.subject like '%$keywords%' OR a.content like '%$keywords%') ";
	}
		
	/* Get Options */
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainertype');
	$trainertype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('trainingtype');
	$trainingtype=$db->getAll($sql);

	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('budget');
	$budget=$db->getAll($sql);
	
	$sql = "SELECT * FROM " .$GLOBALS['ecs']->table('quoting');
	$quoting=$db->getAll($sql);
	#array_push($quoting,array('num'=>"0",'quotingType'=>"All"));
	
	$fctime= date("Y-m-d",time());
	
	/* ÿһ ڽܽÿһг߱ģunfinished*/
    $sql = 'SELECT a.*,b.budgetType,u.user_name,g.genderType ' .'FROM ' . $GLOBALS['ecs']->table('projects') . ' AS a JOIN '. $GLOBALS['ecs']->table('budget') . ' AS b JOIN ' .$GLOBALS['ecs']->table('users') . ' AS u JOIN ' .$GLOBALS['ecs']->table('gender')." AS g "." WHERE  a.featuredFlag=1 AND a.budget=b.num AND a.uid=u.user_id AND u.sex=g.xid AND a.createdDate='$fctime'".$condition;
	$featurelist=$db->getAll($sql);
	
	$featurecount=count($featurelist);
		
	/* Caculate The Remaining Time of The Project */
	for($i=0; $i<count($featurelist); $i++)
	{
		$createtime=strtotime($featurelist[$i]['createdDate']);
		if($featurelist[$i].quoting == 1)
		{
			$endtime = $createtime + 14 * 86400;
		}
		else
		{
			$endtime = $createtime + 30 * 86400;
		}
	
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours ago";
    	}else if($hours>0){
      		 $temp="$hours hours ago";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes ago";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$featurelist[$i]['lefttime']=$temp;		
	}
	
	/* Get All Projects */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects'). " AS a "." WHERE pid>0 AND status != 0 ".$condition;	
	$tasklist=$db->getAll($sql);
	$taskcount=count($tasklist);
		
	$record_count = $taskcount;
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 10;
	$pager = get_pager('projects.php', array('act' => 'browse'), $record_count, $page, $pagesize);
	$fitness_lists = get_projects_list($pagesize, $pager['start'], $condition, $sort);
	
	/* Caculate The Remaining Time of The Project */
	/*
	for($i=0; $i<count($fitness_lists); $i++)
	{
		$createtime=strtotime($fitness_lists[$i]['createdDate']);
		
		if($fitness_lists[$i].quoting == 1)
		{
			$endtime = $createtime + 14 * 86400;
		}
		else
		{
			$endtime = $createtime + 30 * 86400;
		}
	    
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours ago";
    	}else if($hours>0){
      		 $temp="$hours hours ago";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes ago";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$fitness_lists[$i]['lefttime']=$temp;		
	}
	*/
	
    $smarty->assign('trainertype', $trainertype);
    $smarty->assign('trainingtype', $trainingtype);
	$smarty->assign('budget', $budget);
	$smarty->assign('quoting', $quoting);
	$smarty->assign('trainer_type', $trainer_type);
    $smarty->assign('training_type', $training_type);
	$smarty->assign('budget_type', $budget_type);
	$smarty->assign('quoting_type', $quoting_type);
	$smarty->assign('featurelist', $featurelist);
	$smarty->assign('pager', $pager);
	$smarty->assign('tasklist', $fitness_lists);
	$smarty->assign('featurecount', $featurecount);
	$smarty->assign('taskcount', $taskcount);
	
    $smarty->display('projects_browse.dwt');
}

/*------------------------------------------------------ */
//-- Add Task Process 1
/*------------------------------------------------------ */
elseif ($action == 'act_add')
{
	/* Check If Login */
	if (empty($_SESSION['user_id']))
	{
		if($_POST['change_tab'] == 'register')
		{
			include_once(ROOT_PATH . 'includes/lib_passport.php');

        	$username = isset($_POST['username']) ? trim($_POST['username']) : '';
        	$password = isset($_POST['password_register']) ? trim($_POST['password_register']) : '';
			$confirm_password = isset($_POST['confirm_password']) ? trim($_POST['confirm_password']) : '';
        	$email    = isset($_POST['email_register']) ? trim($_POST['email_register']) : '';
        	$back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';

        	if (strlen($password) < 6)
        	{
            	show_message($_LANG['passport_js']['password_shorter']);
        	}

        	if (strpos($password, ' ') > 0)
        	{
            	show_message($_LANG['passwd_balnk']);
        	}
			
			if($password != $confirm_password)
			{
				show_message("Confirm password is different with password!");
			}

        	if (register($username, $password, $email, 2) == false)
        	{
            	$err->show($_LANG['sign_up'], 'user.php?act=register');
        	}   
		}
		else
		{
			$username = isset($_POST['email_login']) ? trim($_POST['email_login']) : '';
    		$password = isset($_POST['password_login']) ? trim($_POST['password_login']) : '';
    		$back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';
		
    		if ($user->login($username, $password,isset($_POST['remember'])))
    		{
        		update_user_info();
       		
    		}
    		else
    		{
        		$_SESSION['login_fail'] ++ ;
        		show_message("You are not member, please register!", $_LANG['relogin_lnk'], 'projects.php', 'error');
    		}
		}
	}
	
	if($_SESSION['user_type'] != 2)
	{
		show_message($_LANG['not_exerciser'], $_LANG['back_up_page'], 'user.php', 'info');
	}
	$smarty->assign('login_flag', 1);
	
	$_SESSION['subject'] = isset($_POST['subject']) ? trim($_POST['subject']) : '';
	$_SESSION['trainertype'] = isset($_POST['trainertype']) ? intval($_POST['trainertype']) : 0;
	$_SESSION['trainingtype'] = isset($_POST['trainingtype']) ? intval($_POST['trainingtype']) : 0;
	$_SESSION['sessions'] = isset($_POST['sessions']) ? intval($_POST['sessions']) : 0;
	$_SESSION['length'] = isset($_POST['length']) ? intval($_POST['length']) : 0;
	$_SESSION['budget'] = isset($_POST['budget']) ? intval($_POST['budget']) : 0;
	$_SESSION['quoting'] = isset($_POST['quoting']) ? intval($_POST['quoting']) : 0;
	$_SESSION['province'] = isset($_POST['province']) ? trim($_POST['province']) : '';
	$_SESSION['friendsnum'] = isset($_POST['friendsnum']) ? intval($_POST['friendsnum']) : 0;
	$_SESSION['specialReq'] = isset($_POST['special']) ? trim($_POST['special']) : '';
	$_SESSION['content'] = isset($_POST['content']) ? trim($_POST['content']) : '';
         
	/* Check The Input */ 
    if (strlen($_SESSION['subject']) < 2)
    {
        show_message($_LANG['subject_short']);
    }
		
    if (strlen($_SESSION['content']) < 6)
    {
        show_message($_LANG['content_short']);
    }
			
	/* Get Budget Type Information */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('budget')." WHERE num = '".$_SESSION['budget']."' ";
	$budget = $db->getRow($sql);
	
	/* Get Quoting Type Information */
	$sql = "SELECT * "." FROM " . $ecs->table('quoting')." WHERE num = '".$_SESSION['quoting']."' ";
	$quoting = $db->getRow($sql);
			      
	$smarty->assign('budgetType', $budget['budgetType']);
	$smarty->assign('quotingType', $quoting['quotingType']);	
	
	$fctime= date("Y-m-d H:i:s",time());
	if($_SESSION['quoting'] == 1)
	{
		$endtime= time() + 14*24*60*60;
	}elseif($_SESSION['quoting'] == 2)
	{
		$endtime= time() + 30*24*60*60;
	}
	$endtime= date("Y-m-d H:i:s",$endtime);	
				
	/* Insert Task Information Into Database */	
	$sql = "INSERT INTO " . $ecs->table('projects') . "(uid,subject,trainertype,trainingtype,sessions,length,budget,quoting,city,friends,specialReq,content,createdDate,endDate,status) VALUES ('" . $_SESSION['user_id'] . "', '" . $_SESSION['subject'] . "', '" . $_SESSION['trainertype'] . "', '" . $_SESSION['trainingtype'] . "','" . $_SESSION['sessions'] . "', '" . $_SESSION['length'] . "', '" . $_SESSION['budget'] . "','" . $_SESSION['quoting'] . "', '" . $_SESSION['province'] . "', '" . $_SESSION['friendsnum'] . "', '" . $_SESSION['specialReq'] . "','" . $_SESSION['content'] . "', '" . $fctime . "', '" . $endtime . "', '0')";
	
    if($db->query($sql) != false)
	{
		$sql = "SELECT pid "." FROM " . $ecs->table('projects')." WHERE uid = '".$_SESSION['user_id']."' AND subject='".$_SESSION['subject']."'  ";
		$pid = $db->getRow($sql);
		$smarty->assign('pid', $pid['pid']);
		
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects').' AS p JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u JOIN '.$GLOBALS['ecs']->table('budget') . ' AS b JOIN '.$GLOBALS['ecs']->table('trainertype').' AS t JOIN ' .$GLOBALS['ecs']->table('trainingtype').' AS tt JOIN ' .$GLOBALS['ecs']->table('sessionstype').' AS s JOIN ' .$GLOBALS['ecs']->table('sessionlength').' AS l '." WHERE p.pid='$pid[pid]' AND p.uid=u.user_id AND p.budget=b.num AND p.trainerType=t.num AND p.trainingType=tt.num AND p.sessions=s.num AND p.length=l.num ";
		
		$project= $db->getRow($sql);
		$project['friends'] = $project['friends'] + 1;
		
		$smarty->assign('project_info', $project);
		$smarty->display('project_add2.dwt');	
	}
	else
	{
		show_message("Sorry, Launch Project Failed, Please Try Again!", $_LANG['back_up_page'], 'addtask.php', 'info');
	}  			 
}

/*------------------------------------------------------ */
//-- Add Task Process 1
/*------------------------------------------------------ */
elseif ($action == 'act_edit')
{
	/*获取项目id*/
	$getpid  = isset($_REQUEST['pid']) ? trim($_REQUEST['pid']) : 'nothing';
				
	$_SESSION['subject'] = isset($_POST['subject']) ? trim($_POST['subject']) : '';
	$_SESSION['trainertype'] = isset($_POST['trainertype']) ? intval($_POST['trainertype']) : 0;
	$_SESSION['trainingtype'] = isset($_POST['trainingtype']) ? intval($_POST['trainingtype']) : 0;
	$_SESSION['sessions'] = isset($_POST['sessions']) ? intval($_POST['sessions']) : 0;
	$_SESSION['length'] = isset($_POST['length']) ? intval($_POST['length']) : 0;
	$_SESSION['budget'] = isset($_POST['budget']) ? intval($_POST['budget']) : 0;
	$_SESSION['quoting'] = isset($_POST['quoting']) ? intval($_POST['quoting']) : 0;
	$_SESSION['province'] = isset($_POST['province']) ? trim($_POST['province']) : '';
	$_SESSION['friendsnum'] = isset($_POST['friendsnum']) ? intval($_POST['friendsnum']) : 0;
	$_SESSION['content'] = isset($_POST['content']) ? trim($_POST['content']) : '';
         
	/* Check The Input */ 
    if (strlen($_SESSION['subject']) < 2)
    {
        show_message($_LANG['subject_short']);
    }
		
    if (strlen($_SESSION['content']) < 6)
    {
        show_message($_LANG['content_short']);
    }
			
	/* Get Budget Type Information */
	$sql = "SELECT * "." FROM " . $ecs->table('budget')." WHERE num = '".$_SESSION['budget']."' ";
	$budget = $db->getRow($sql);
	
	/* Get Quoting Type Information */
	$sql = "SELECT * "." FROM " . $ecs->table('quoting')." WHERE num = '".$_SESSION['quoting']."' ";
	$quoting = $db->getRow($sql);
			
	$smarty->assign('budgetType', $budget['budgetType']);
	$smarty->assign('quotingType', $quoting['quotingType']);	
	
	$fctime= date("Y-m-d H:i:s",time());
	if($_SESSION['quoting'] == 1)
	{
		$endtime= time() + 14*24*60*60;
	}elseif($_SESSION['quoting'] == 2)
	{
		$endtime= time() + 30*24*60*60;
	}
	$endtime= date("Y-m-d H:i:s",$endtime);	
					
	$sql = "UPDATE " . $ecs->table('projects') . "SET subject='" . $_SESSION['subject'] . "',trainertype='" . $_SESSION['trainingtype'] . "',trainingtype='" . $_SESSION['trainertype'] . "',sessions='" . $_SESSION['sessions'] . "',length='" . $_SESSION['length'] . "',budget='" . $_SESSION['budget'] . "',quoting='" . $_SESSION['quoting'] . "',city='" . $_SESSION['province'] . "',friends='" . $_SESSION['friendsnum'] . "',content='" . $_SESSION['content'] . "',createdDate='" . $fctime . "',endDate='" . $endtime . "',status=0". " WHERE pid='$getpid' ";
	
    if($db->query($sql) != false)
	{
		$smarty->assign('pid', $getpid);
		
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects').' AS p JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u JOIN '.$GLOBALS['ecs']->table('budget') . ' AS b JOIN '.$GLOBALS['ecs']->table('trainertype').' AS t JOIN ' .$GLOBALS['ecs']->table('trainingtype').' AS tt JOIN ' .$GLOBALS['ecs']->table('sessionstype').' AS s JOIN ' .$GLOBALS['ecs']->table('sessionlength').' AS l '." WHERE p.pid='$getpid' AND p.uid=u.user_id AND p.budget=b.num AND p.trainerType=t.num AND p.trainingType=tt.num AND p.sessions=s.num AND p.length=l.num ";
		
		$project= $db->getRow($sql);
		$project['friends'] = $project['friends'] + 1;
		
		$smarty->assign('project_info', $project);		
		$smarty->display('project_add2.dwt');
	}
	else
	{
		show_message("Sorry, Launch Project Failed, Please Try Again!", $_LANG['back_up_page'], 'projects.php', 'info');
	}  
}


/*------------------------------------------------------ */
//-- Add Task Process OK
/*------------------------------------------------------ */
elseif ($action == 'act_addok')
{
	/*获取项目id*/
	$getpid  = isset($_REQUEST['pid']) ? intval($_REQUEST['pid']) : 0;	
	//$apply_for_feature = isset($_POST['apply_for_feature']) ? intval($_POST['apply_for_feature']) : 0;
	/* Insert Task Information Into Database */	
	$sql = "UPDATE " . $ecs->table('projects') . " SET status=1 "." WHERE pid='$getpid' ";
	
    if($db->query($sql) != false)
	{
		/* Add Task Successfully */	
		show_message("Congratulation! List published!", $_LANG['back_up_page'], "projects.php?act=view_project&pid=".$getpid."", 'info');
	}
	else
	{
		show_message("Sorry, Launch Project Failed, Please Try Again!", $_LANG['back_up_page'], 'projects.php', 'info');
	}   
}

/*------------------------------------------------------ */
//-- Add Task Proposal
/*------------------------------------------------------ */
elseif ($action == 'act_proposal')
{
	/* Check If Trainer */	
	if($_SESSION[user_type] == 1)
	{
		$addproposal=$_POST['addproposal'];
		$addproposal['pid']=$_POST['pid'];
		$addproposal['uid']=$_SESSION['user_id'];
		$addproposal['tid']=$value['tid'];
		$addproposal['priceFlag']=0;
		
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals')."WHERE uid='".$_SESSION['user_id']."' AND pid='".$_POST['pid']."' ";
		$num = $db->getRow($sql);
		
		if($num)
		{
			$addproposal['proposaledDate']= date("Y-m-d H:i:s",time());
			$addproposal['accessories']= isset($filename)?$filename:'';
			$addproposal['approxPrice'] = isset($addproposal['approxPrice'])?floatval($addproposal['approxPrice']):0.00;
			
			/* Update Database */			
			$sql = "UPDATE " . $ecs->table('proposals') . " SET pid='". $addproposal['pid']. "', uid='". $addproposal['uid'] . "',tid='" . $addproposal['tid'] . "', proposaledTrainingType='" . $addproposal['proposaledTrainingType'] . "', priceFlag='" . $addproposal['priceFlag'] . "', proposal_content='" .$addproposal['proposal_content'] . "', approxPrice='" . $addproposal['approxPrice'] . "', priceRangeFrom='" . $addproposal['rangePrice_from'] . "',  priceRangeTo='". $addproposal['rangePrice_to'] . "', proposalSubject='". $addproposal['proposalSubject'] . "', phoneNumber='". $addproposal['phoneNumber'] . "', proposaledDate = '" . $addproposal['proposaledDate'] . "', accessories = '" . $addproposal['accessories'] . "' WHERE ppid='".$num['ppid']."' ";
			
			$db->query($sql);
			
			show_message("Your proposal has been updated!", $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		}
		
		if($_FILES['userfile']['size']!=0)
		{
			/* Save The Accessories */
			if($_FILES['userfile']['error']>0 && $_FILES['userfile']['error']<4)
			{
				switch($_FILES['userfile']['error'])
				{
					case 1:	$msg='File exceeded upload_max_filesize';break;
					case 2:	$msg='File exceeded max_file_size';break;
					case 3: $msg='File only partially uploaded';break;
				}
				show_message($msg, $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
			}

			$filename = "$addproposal[pid]_"."$addproposal[uid]_".$_FILES['userfile']['name'];
			$upfile = './proposals/'.$filename;

			if(is_uploaded_file($_FILES['userfile']['tmp_name']))
			{
				if(!move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile))
				{
					show_message('Problem: Could not move file to destination directory', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
				}
			}
			else
			{			
				show_message('Problem: Possible file upload attack. Filename:'.$_FILES['userfile']['name'], $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
			}
		}
	
		$addproposal['proposaledDate']= date("Y-m-d H:i:s",time());
		$addproposal['accessories']= isset($filename)?$filename:'';
		$addproposal['approxPrice'] = isset($addproposal['approxPrice'])?floatval($addproposal['approxPrice']):0.00;
		/* Insert Into Database */
		$sql = "INSERT INTO " . $ecs->table('proposals') . "(pid,uid,tid,proposaledTrainingType,priceFlag, proposal_content,approxPrice, priceRangeFrom, priceRangeTo, proposalSubject, phoneNumber, proposaledDate,accessories) VALUES ('" . $addproposal['pid'] . "', '" . $addproposal['uid'] . "', '" . $addproposal['tid'] . "', '" . $addproposal['proposaledTrainingType'] . "','" . $addproposal['priceFlag'] . "', '" .$addproposal['proposal_content'] . "', '" . $addproposal['approxPrice'] . "', '" . $addproposal['rangePrice_from'] . "', '". $addproposal['rangePrice_to'] . "', '". $addproposal['proposalSubject'] . "','" .$addproposal['phoneNumber'] . "','" . $addproposal['proposaledDate'] . "', '" . $addproposal['accessories'] . "')";
    	if($db->query($sql) == false)
		{
			show_message($_LANG['addtask_fail'], $_LANG['back_up_page'], 'projects.php', 'info');
		} 
		
		/* projectsEnter + 1 */
		$sql = "SELECT projects_entered "." FROM " . $GLOBALS['ecs']->table('users')."WHERE user_id='".$_SESSION['user_id']."' ";
		$value = $db->getRow($sql);
		$value['projects_entered'] = $value['projects_entered'] + 1;
		
		$sql = "UPDATE " . $ecs->table('users') . " SET projects_entered='".$value['projects_entered']."' "." WHERE user_id='".$_SESSION['user_id']."' ";
		$db->query($sql);
		
		/* proposalsNum + 1 */
		$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects'). " AS p JOIN ". $GLOBALS['ecs']->table('users'). " AS u " . "WHERE p.pid='".$addproposal[pid]."' AND p.uid =u.user_id ";
		$value = $db->getRow($sql);
		$value['proposalsNum'] = $value['proposalsNum'] + 1;	
		$sql = "UPDATE " . $ecs->table('projects') . " SET proposalsNum='".$value[proposalsNum]."' "."WHERE pid='".$addproposal[pid]."' ";
		
		send_alert_email($value['user_id'], $value['user_name'], $value['email'], 'proposal_notice', 'user.php?act=login');
			
		if($db->query($sql) != false)
		{
			/* Modify Information Successfully! */	
			show_message('Congratulation! Offer submitted!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		}
		else
		{
			show_message('Proposal Failed, please try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		} 
	}
	else
	{
		show_message(' You are not trainer, please register as trainer, then try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
	}
}

/*------------------------------------------------------ */
//-- Add Task Proposal
/*------------------------------------------------------ */
elseif ($action == 'edit_proposal')
{
	/* Check If Trainer */	
	if($_SESSION[user_type] == 1)
	{
		$addproposal=$_POST['addproposal'];
    	$addproposal['pid']=$_POST['pid'];
		$addproposal['uid']=$_SESSION['user_id'];
		$addproposal['tid']=$value['tid'];
		$addproposal['priceFlag']=0;
		$ppid=$_POST['ppid'];		
					
		$addproposal['proposaledDate']= date("Y-m-d H:i:s",time());		
		$addproposal['approxPrice'] = isset($addproposal['approxPrice'])?floatval($addproposal['approxPrice']):0.00;
		/* Insert Into Database */
		$sql = "UPDATE " . $ecs->table('proposals') . " SET proposaledTrainingType='" . $addproposal['proposaledTrainingType'] . "' , approxPrice='" . $addproposal['approxPrice'] . "' ,proposalSubject='" . $addproposal['proposalSubject'] . "' ,proposaledDate='" . $addproposal['proposaledDate'] . "' ,proposal_content='" . $addproposal['proposal_content'] . "' WHERE ppid='$ppid' ";
    			
		if($db->query($sql) != false)
		{
			/* Modify Information Successfully! */	
			show_message('Congratulation! proposal edited!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		}
		else
		{
			show_message('Edit proposal Failed, please try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		} 
	}
	else
	{
		show_message(' You are not trainer, please register as trainer, then try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
	}
}

/*------------------------------------------------------ */
//-- Add Task Proposal
/*------------------------------------------------------ */
elseif ($action == 'add_watch')
{
	/*获取项目id*/
	$getpid  = isset($_REQUEST['pid']) ? intval($_REQUEST['pid']) : 0;	
	if(isset($_SESSION[user_id]) && $_SESSION[user_id] != 0)
	{
		if($getpid != 0)
		{		
			$sql = "INSERT INTO " . $ecs->table('watchlist') . "(user_id,pid) VALUES ('" . $_SESSION['user_id'] . "', '" . $getpid. "')";
    		if($db->query($sql) == false)
			{
				show_message($_LANG['addtask_fail'], $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
			} 
			else
			{
				show_message("Add to watch list successfully", $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
			}
		}
		else
		{
			show_message(' There are no pid, then try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
		}
	}
	else
	{
		show_message(' You are member, please register as a member, then try again!', $_LANG['back_up_page'], 'projects.php?act=browse', 'info');
	}
}

/*------------------------------------------------------ */
//-- exerciser 的 my fitness listings
/*------------------------------------------------------ */
elseif ($action == 'my_fitness_listings')
{
		
	/* Get Projects Information */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('projects')." WHERE uid = '".$_SESSION['user_id']."' ";
	$projectslist= $db->getAll($sql);
	$record_count = count($projectslist);
		
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 10;
	
	$pager = get_pager('projects.php', array('act' => 'my_fitness_listings'), $record_count, $page, $pagesize);
	$temp = " AND uid='".$_SESSION['user_id']."' ";
	$fitness_lists = get_all_projects_list($pagesize, $pager['start'], $temp);	
		
	$cftime=date("Y-m-d",time());		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals'). ' AS pp JOIN '. $GLOBALS['ecs']->table('projects').' AS p  '." WHERE p.uid = '".$getuid."' AND p.uid=pp.uid AND pp.proposaledDate='$cftime' ";		
	$newproposallist = $db->getAll($sql);
	$newproposalaccount = count($newproposallist);	
		
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals'). ' AS pp JOIN '. $GLOBALS['ecs']->table('projects').' AS p  '." WHERE p.uid = '".$getuid."' AND p.uid=pp.uid AND pp.proposaledDate='$cftime' AND pp.awarded=1 AND pp.accepted=1 ";		
	$newacceptedlist = $db->getAll($sql);
	$newacceptedaccount = count($newacceptedlist);	
	
	include_once(ROOT_PATH .'includes/lib_clips.php');
	$smarty->assign('info',   get_user($_SESSION['user_id']));
	$smarty->assign('exerciser', $exerciser);
	$smarty->assign('newproposalaccount', $newproposalaccount);
	$smarty->assign('newacceptedaccount', $newacceptedaccount);
	$smarty->assign('projectslist', $fitness_lists);
	$smarty->assign('pager', $pager);
	$smarty->display('user_dealings.dwt');
}

/*------------------------------------------------------ */
//-- trainer 的 my clients proposals
/*------------------------------------------------------ */
elseif ($action == 'my_clients_proposals')
{	
	/* Get Proposals Information */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals') . ' AS pp JOIN ' . $GLOBALS['ecs']->table('projects') .' AS p ' . " WHERE pp.uid='".$_SESSION[user_id]."' AND pp.pid=p.pid ";
	$proposalslist = $db->getAll($sql);	
	$record_count = count($proposalslist);
	
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 10;
	
	$pager = get_pager('projects.php', array('act' => 'my_clients_proposals'), $record_count, $page, $pagesize);
	$proposals_lists = get_proposals_list_by_uid($pagesize, $pager['start'],$_SESSION[user_id]);	
			
	/* Get The Proposal Which is awarded, but not accepted */
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals') .' AS pp JOIN ' . $GLOBALS['ecs']->table('projects') .' AS p ' . " WHERE pp.uid='".$_SESSION[user_id]."' AND pp.awarded=1 AND pp.accepted=0 AND pp.pid=p.pid ";
	$proposalsWonlist = $db->getAll($sql);	
	$record_count = count($proposalsWonlist);
	
	$page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
	$pagesize = 6;
	
	$temp = " AND pp.awarded=1 AND pp.accepted=0 AND pp.pid=p.pid ";
	$pager = get_pager('projects.php', array('act' => 'my_clients_proposals'), $record_count, $page, $pagesize);
	$proposals_won_lists = get_proposals_list_by_uid($pagesize, $pager['start'],$_SESSION[user_id], $temp);	
		
	include_once(ROOT_PATH .'includes/lib_clips.php');
	$smarty->assign('info',   get_user($_SESSION['user_id']));
	$smarty->assign('proposalslist', $proposals_lists);
	$smarty->assign('proposalsWonlist', $proposals_won_lists);
	$smarty->assign('proposalsWonNum', $record_count);
	$smarty->display('user_dealings.dwt');
}

/*------------------------------------------------------ */
//-- 删除选中的Projects
/*------------------------------------------------------ */
elseif($action == 'act_remove_projects')
{
	$checkbox=$_POST['checkbox'];
	
	if(count($checkbox) == 0)
	{
		show_message('You haven\'t chosen any proposls!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}
	else
	{
		$number = count($checkbox);
	}
	
	$sql = "DELETE FROM " . $GLOBALS['ecs']->table('projects') .
                    " WHERE pid in(";
                   	
	for($i=0; $i<$number - 1; $i++)
	{
		$sql = $sql.$checkbox[$i].",";
	}
	$sql = $sql.$checkbox[$number - 1].")";

	if($db->query($sql) != false)
	{
		/* Delete Proposals Successfully! */	
		show_message('Projects delete successfully!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}
	else
	{
		/* Delete Proposals Successfully! */	
		show_message('Sorry, projects delete failed!', $_LANG['back_up_page'], 'projects.php?act=my_fitness_listings', 'info');
	}
}

/*------------------------------------------------------ */
//-- 删除选中的Proposals
/*------------------------------------------------------ */
elseif($action == 'act_remove_proposals')
{
	$checkbox=$_POST['checkbox'];
	
	if(count($checkbox) == 0)
	{
		show_message('You haven\'t chosen any proposls!', $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}
	else
	{
		$number = count($checkbox);
	}
	
	$sql = "DELETE FROM " . $GLOBALS['ecs']->table('proposals') .
                    " WHERE ppid in(";
                   	
	for($i=0; $i<$number - 1; $i++)
	{
		$sql = $sql.$checkbox[$i].",";
		
		/*获取相应pid, 并且删除相应附件*/
		$sql = "SELECT pid,accessories "." FROM " . $GLOBALS['ecs']->table('proposals')."WHERE ppid='".$checkbox[$i]."' ";
		$pid = $db->getRow($sql);
		unlink(ROOT_PATH . '/proposals/'.$pid['accessories']);
		/* proposalsNum - 1 */
		$sql_temp = "SELECT proposalsNum "." FROM " . $GLOBALS['ecs']->table('projects')."WHERE pid='".$pid['pid']."' ";
		$value = $db->getRow($sql_temp);
		$value['proposalsNum'] = $value['proposalsNum'] - 1;	
		$sql_temp = "UPDATE " . $ecs->table('projects') . " SET proposalsNum='".$value[proposalsNum]."' "."WHERE pid='".$pid['pid']."' ";
		if($db->query($sql_temp) == false)
		{
			/* Delete Proposals Successfully! */	
			show_message('Error to update proposals number of project '.$pid['pid'], $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
		}
	}
	$sql = $sql.$checkbox[$number - 1].")";
	/*获取相应pid*/
	$sql_temp = "SELECT pid,accessories "." FROM " . $GLOBALS['ecs']->table('proposals')."WHERE ppid='".$checkbox[$number - 1]."' ";
	$pid = $db->getRow($sql_temp);
	unlink(ROOT_PATH . '/proposals/'.$pid['accessories']);
	/* proposalsNum - 1 */
	$sql_temp = "SELECT proposalsNum "." FROM " . $GLOBALS['ecs']->table('projects')."WHERE pid='".$pid['pid']."' ";
	$value = $db->getRow($sql_temp);
	$value['proposalsNum'] = $value['proposalsNum'] - 1;	
	$sql_temp = "UPDATE " . $ecs->table('projects') . " SET proposalsNum='".$value['proposalsNum']."' "."WHERE pid='".$pid['pid']."' ";
	if($db->query($sql_temp) == false)
	{
		show_message('Error to update proposals number of project '.$pid['pid'], $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}

	if($db->query($sql) != false)
	{		
		/* Delete Proposals Successfully! */	
		show_message('Proposals delete successfully!', $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}
	else
	{
		/* Delete Proposals Successfully! */	
		show_message('Sorry, proposals delete failed!', $_LANG['back_up_page'], 'projects.php?act=my_clients_proposals', 'info');
	}
}

/*------------------------------------------------------ */
//-- Trainer Award Letter Page
/*------------------------------------------------------ */
elseif($action == 'accept_award')
{
	/* Get Project id*/
	$getppid  = isset($_REQUEST['ppid']) ? trim($_REQUEST['ppid']) : 'nothing';
	
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN ' . $GLOBALS['ecs']->table('projects') . ' AS p JOIN ' .$GLOBALS['ecs']->table('users') . ' AS u ' . " WHERE pp.ppid='$getppid' AND pp.pid=p.pid AND p.uid=u.user_id ";
	$acceptTheAwardLetter = $db->getRow($sql);

	$smarty->assign('username', $_SESSION['user_name']);
	$smarty->assign('acceptTheAwardLetter', $acceptTheAwardLetter);
	$smarty->display('accept_award.dwt');
}

/*------------------------------------------------------ */
//-- Trainer Award Letter Page
/*------------------------------------------------------ */
elseif($action == 'act_accept_award')
{
	/* Get Project id*/
	$getppid  = isset($_REQUEST['ppid']) ? trim($_REQUEST['ppid']) : 'nothing';
	$getpid  = isset($_REQUEST['pid']) ? trim($_REQUEST['pid']) : 'nothing';
	$back_act = $GLOBALS['_SERVER']['HTTP_REFERER'];
	
	/*get client information*/
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('users').' AS u JOIN '.$GLOBALS['ecs']->table('projects') . ' AS p '."WHERE p.pid='$getpid' AND u.user_id=p.uid  ";
	$client = $db->getRow($sql);
	send_alert_email($client['user_id'], $client['user_name'], $client['email'], 'accept_notice', 'user.php?user_id='.$client['user_id']);

	$sql = "UPDATE " . $ecs->table('proposals') . " SET accepted=1 "."WHERE ppid='".$getppid."' ";
	$db->query($sql);
	
	$sql = "UPDATE " . $ecs->table('projects') . " SET status=3 "." WHERE pid='".$getpid."'";
	if($db->query($sql) != false)
	{
		show_message('You just accepted the client\'s award!', $_LANG['back_up_page'], $back_act, 'info');
	}
	else
	{
		how_message("Set Project Status to 3 failled!", $_LANG['back_up_page'], $back_act, 'info');
	}	
}

/*------------------------------------------------------ */
//-- Get City
/*------------------------------------------------------ */
elseif($action == 'act_get_address')
{
	#$sql = "SELECT city_name FROM " .$GLOBALS['ecs']->table('city');
	$sql = 'SELECT * ' .'FROM ' . $GLOBALS['ecs']->table('city'). " AS a LEFT JOIN ". $GLOBALS['ecs']->table('country'). " AS c ON a.country_id = c.country_id LEFT JOIN " . $GLOBALS['ecs']->table('state'). " AS s ON a.state_id = s.state_id " ;
	$a=$db->getAll($sql);
   
	//get the q parameter from URL
	$q=trim($_GET["q"]);

	//lookup all hints from array if length of q>0
	if (strlen($q) > 0)
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			if (strtolower($q)==strtolower(substr($a[$i]['city_name'],0,strlen($q))))
    		{
    			if ($hint=="")
      			{
      				$hint="<li style='background:#F2F2F2 ; width: 300px; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'>".$a[$i]['city_name'].",".$a[$i]['state_name'].",".$a[$i]['country_name']."</li>";
      			}
    			else
      			{
      				$hint=$hint." <li style='background:#F2F2F2 ; width: 300px; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;'  onclick='get_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)' > ".$a[$i]['city_name'].",".$a[$i]['state_name'].",".$a[$i]['country_name']."</li>";
      			}
    		}
  		}
	}

	//Set output to "no suggestion" if no hint were found
	//or to the correct values
	if ($hint == "")
	{
		$response="";
	}
	else
	{
		$response=$hint;
	}

	//output the response
	echo $response;
}

/*------------------------------------------------------ */
//-- Get City
/*------------------------------------------------------ */
elseif($action == 'act_get_city')
{
	#$sql = "SELECT city_name FROM " .$GLOBALS['ecs']->table('city');
	$sql = 'SELECT * ' .'FROM ' . $GLOBALS['ecs']->table('city') ;
	$a=$db->getAll($sql);
   
	//get the q parameter from URL
	$q=trim($_GET["q"]);

	//lookup all hints from array if length of q>0
	if (strlen($q) > 0)
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			if (strtolower($q)==strtolower(substr($a[$i]['city_name'],0,strlen($q))))
    		{
    			if ($hint=="")
      			{
      				$hint="<li style='background:#F2F2F2 ; width: 300px; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_city_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'>".$a[$i]['city_name']."</li>";
      			}
    			else
      			{
      				$hint=$hint." <li style='background:#F2F2F2 ; width: 300px; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;'  onclick='get_city_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)' > ".$a[$i]['city_name']."</li>";
      			}
    		}
  		}
	}
	else
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			
    			
      		$hint=$hint." <li style='background:#F2F2F2 ; width: 300px; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;'  onclick='get_city_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)' > ".$a[$i]['city_name']."</li>";
      			
  		}
	}

	//Set output to "no suggestion" if no hint were found
	//or to the correct values
	if ($hint == "")
	{
		$response="";
	}
	else
	{
		$response=$hint;
	}

	//output the response
	echo $response;
}


/*------------------------------------------------------ */
//-- Get Country
/*------------------------------------------------------ */
elseif($action == 'act_get_country')
{
	$sql = "SELECT country_name FROM " .$GLOBALS['ecs']->table('country');
	$a=$db->getAll($sql);
   
	//get the q parameter from URL
	$q=trim($_GET["q"]);

	//lookup all hints from array if length of q>0
	if (strlen($q) > 0)
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			if (strtolower($q)==strtolower(substr($a[$i]['country_name'],0,strlen($q))))
    		{
    			if ($hint=="")
      			{
      				$hint="<li style='background:#F2F2F2 ; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_country_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'>".$a[$i]['country_name']."</li>";
      			}
    			else
      			{
      				$hint=$hint." <li style='background:#F2F2F2 ; height: 20px;   background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_country_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'> ".$a[$i]['country_name']."</li>";
      			}
    		}
  		}
	}
	else
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			
      		$hint=$hint." <li style='background:#F2F2F2 ; height: 20px;   background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_country_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'> ".$a[$i]['country_name']."</li>";
      			
  		}
	}

	//Set output to "no suggestion" if no hint were found
	//or to the correct values
	if ($hint == "")
	{
		$response="";
	}
	else
	{
		$response=$hint;
	}

	//output the response
	echo $response;
}


/*------------------------------------------------------ */
//-- Get State
/*------------------------------------------------------ */
elseif($action == 'act_get_state')
{
	$sql = "SELECT state_name FROM " .$GLOBALS['ecs']->table('state');
	$a=$db->getAll($sql);
   
	//get the q parameter from URL
	$q=trim($_GET["q"]);

	//lookup all hints from array if length of q>0
	if (strlen($q) > 0)
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			if (strtolower($q)==strtolower(substr($a[$i]['state_name'],0,strlen($q))))
    		{
    			if ($hint=="")
      			{
      				$hint="<li style='background:#F2F2F2 ; height: 20px;  background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_state_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)'>".$a[$i]['state_name']."</li>";
      			}
    			else
      			{
      				$hint=$hint." <li style='background:#F2F2F2 ; height: 20px;   background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_state_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)' > ".$a[$i]['state_name']."</li>";
      			}
    		}
  		}
	}
	else
	{
		$hint="";
		for($i=0; $i<count($a); $i++)
  		{
  			
      		$hint=$hint." <li style='background:#F2F2F2 ; height: 20px;   background-repeat:repeat; padding-left:20px; margin-top: 0px; font-size:12px; list-style:none;' onclick='get_state_string(this)' onmouseover='change_color(this)' onmouseout='back_color(this)' > ".$a[$i]['state_name']."</li>";
      			
  		}
	}

	//Set output to "no suggestion" if no hint were found
	//or to the correct values
	if ($hint == "")
	{
		$response="";
	}
	else
	{
		$response=$hint;
	}

	//output the response
	echo $response;
}



/**
 * 
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_projects_list($num, $start, $temp='', $sort='pid')
{
    /*   */	
	$sql = 'SELECT a.*,b.budgetType,u.user_name, u.user_id, u.firstname, u.lastname, u.photo, u.sex, g.genderType, t.trainingType ' .'FROM ' . $GLOBALS['ecs']->table('projects') . ' AS a JOIN '. $GLOBALS['ecs']->table('budget') . ' AS b JOIN ' .$GLOBALS['ecs']->table('users') . ' AS u JOIN ' .$GLOBALS['ecs']->table('gender')." AS g JOIN ". $GLOBALS['ecs']->table('trainingtype'). " AS t ". " WHERE a.budget=b.num AND a.uid=u.user_id AND u.sex=g.xid AND a.trainingType=t.num AND a.status != 0 ".$temp;
	$sql = $sql." ORDER by ". $sort." DESC LIMIT ".$start.",".$num;
	$res = $GLOBALS['db']->getAll($sql);
		
	/* Caculate The Remaining Time of The Project */
	for($i=0; $i<count($res); $i++)
	{
		$createtime=strtotime($res[$i]['createdDate']);
		
		if($res[$i]['quoting'] == 1)
		{
			$endtime = $createtime + 14 * 86400;
		}
		else
		{
			$endtime = $createtime + 30 * 86400;
		}
	
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours";
    	}else if($hours>0){
      		 $temp="$hours hours";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$res[$i]['lefttime']=$temp;	
		
		if(	$temp == "over")
		{
			$sql = "UPDATE " . $GLOBALS['ecs']->table('projects') . " SET status=5 "." WHERE pid='".$res[$i]['pid']."'";
						
			$GLOBALS['db']->query($sql);
			$res[$i]['status'] = 5;
		}	
	}
	
    return $res;
}

/**
 * get all projects of the client, include status eq 0
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_all_projects_list($num, $start, $temp='', $sort='pid')
{
    /*   */	
	$sql = 'SELECT a.*,b.budgetType,u.user_name, u.user_id, u.firstname, u.lastname, g.genderType, t.trainingType ' .'FROM ' . $GLOBALS['ecs']->table('projects') . ' AS a JOIN '. $GLOBALS['ecs']->table('budget') . ' AS b JOIN ' .$GLOBALS['ecs']->table('users') . ' AS u JOIN ' .$GLOBALS['ecs']->table('gender')." AS g JOIN ". $GLOBALS['ecs']->table('trainingtype'). " AS t ". " WHERE a.budget=b.num AND a.uid=u.user_id AND u.sex=g.xid AND a.trainingType=t.num  ".$temp;
	$sql = $sql." ORDER by ". $sort." DESC LIMIT ".$start.",".$num;
	$res = $GLOBALS['db']->getAll($sql);
		
	/* Caculate The Remaining Time of The Project */
	for($i=0; $i<count($res); $i++)
	{
		$createtime=strtotime($res[$i]['createdDate']);
		
		if($res[$i]['quoting'] == 1)
		{
			$endtime = $createtime + 14 * 86400;
		}
		else
		{
			$endtime = $createtime + 30 * 86400;
		}
	
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours";
    	}else if($hours>0){
      		 $temp="$hours hours";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$res[$i]['lefttime']=$temp;		
	}
	
    return $res;
}


/**
 * 
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_proposals_list($num, $start, $pid, $order='DESC', $sort='ppid')
{
    /*   */	
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ' ." WHERE pp.pid='".$pid."' AND pp.uid=u.user_id ";
	$sql = $sql." ORDER by ". $sort." ".$order." LIMIT ".$start.",".$num;
	$res = $GLOBALS['db']->getAll($sql);
	
    return $res;
}

/**
 * 
 *
 * @param   integer $num
 * @param   integer $start
 *
 * @return  array
 */
function get_proposals_list_by_uid($num, $start, $uid, $temp='', $order='DESC', $sort='ppid')
{
    /*   */	
	$sql = "SELECT * "." FROM " . $GLOBALS['ecs']->table('proposals').' AS pp JOIN ' . $GLOBALS['ecs']->table('projects') .' AS p ' . " WHERE pp.uid='".$uid."' AND pp.pid=p.pid ". $temp;
	$sql = $sql." ORDER by ". $sort." ".$order." LIMIT ".$start.",".$num;
	$res = $GLOBALS['db']->getAll($sql);
	
	/* Caculate The Remaining Time of The Proposals */
	for($i=0; $i<count($res); $i++)
	{		
		$proposaledtime=strtotime($res[$i]["proposaledDate"]);
	
		$nowtime=time();
		
		if($proposaledtime == $nowtime)
		{
			$res[$i]['timeago']="0 days 0 hours ago";
		}
		else
		{
			$days=($nowtime-$proposaledtime)/86400;
    		$new_day=explode('.',$days);
		
    		$hours=floor(($nowtime-$proposaledtime)/3600);

   	 		$hours_day=$hours-($new_day[0]*24);

    		$minutes=floor(($nowtime-$proposaledtime)/60);

    		if($new_day[0]>0){
       		 	$temp="$new_day[0] days $hours_day hours ago";
    		}else if($hours>0){
      		 	$temp="$hours hours ago";
   			}else if($hours_day==0){
      		 	$temp="$minutes minutes ago";
    		}else if($hours_day<0){
     		 	$temp="over";
    		}
			$res[$i]['timeago']=$temp;
		}   	
				
		$endtime=strtotime($res[$i]['awardDate']);					
		$nowtime=time();
    	$days=($endtime - $nowtime)/86400;
    	$new_day=explode('.',$days);
	
    	$hours=floor(($endtime - $nowtime)/3600);

   	 	$hours_day=$hours-($new_day[0]*24);

    	$minutes=floor(($endtime - $nowtime)/60);

    	if($new_day[0]>0){
       		 $temp="$new_day[0] days $hours_day hours";
    	}else if($hours>0){
      		 $temp="$hours hours";
   		}else if($hours_day==0){
      		 $temp="$minutes minutes";
    	}else if($hours_day<0){
     		 $temp="over";
    	}
		$res[$i]['lefttime']=$temp;			
	}
	
    return $res;
}


?>